<?php
 // START GET DATA THEO GET  METHOD-------------
 

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	require_once 'libraries/function/validateAjax.php';
	
	if(isset($_GET['page']) && $_GET['case']==1){
		
		if($_GET['page'] % LOAD_TIME !=0){

			$order="id desc";
			
			if(isset($_GET['ext'])){
				
				switch($_GET['ext']){
					case 'views':
					case 'likes':
					case 'comments':
					$order= $_GET['ext']." ".$_GET['sort'];
					break;
					case "date":
					$order= "id ".$_GET['sort'];
					break;
					/*
					case 'picture': $where=' where is_image=1';break;
					case 'video': $where=' where is_video=1';break;
					case 'text': $where=' where is_text=1';break;
					*/
				}
			$url="";
			}
			
			$cache=new Cache;
			$sql ="select id,cat_id,post_id,username,id_album ,is_image,is_video,is_text from index_post order by ".$order;
			
			$sql2="select id from index_post ".$where;
		
			$pager = new Pagination($sql,LOAD_ITEMS,4,$url,5,"post");
			$pager->setDebug(false);
			$data[info] = $pager->paginate($cache,$sql2);
			$data['page'] = $pager->get_num_page();
			
			if($_GET['page'] > $data['page']){
				exit();
			}
			
			
			// END OF GET DATA THEO GET MOTHOD
					// NGUOC LAI THI RENDER GRID ITEM, MASORY WILL APPEND IT
			
				
				if($_SESSION['list_news_list'] == 1){
				
					post_render_grid_item_list($data['info']);
				}else{
					post_render_grid_item($data['info']);
				}
				exit();
			
		 }else{
		
		 exit();
		 }
	}
	
	// LOAD MORE ITEM WITH GET TYPE VIDEO,TEXT, IMAGE AND CASE ==2-------------------------------------------------
	if(isset($_GET['page']) && $_GET['case']==2){
	
		if($_GET['page'] % LOAD_TIME !=0){
		 	
			$order=" id desc";
		
			switch($_GET['type']){
			case 'picture': $where=' where is_image=1';break;
			case 'video': $where=' where is_video=1';break;
			case 'text': $where=' where is_text=1';break;
			
	}
			
			if(isset($_GET['ext'])){
				
				switch($_GET['ext']){
					case 'views':
					case 'likes':
					case 'comments':
					$order= $_GET['ext']." ".$_GET['sort'];
					break;
					case "date":
					$order= "id ".$_GET['sort'];
					/*
					case 'picture': $where=' where is_image=1';break;
					case 'video': $where=' where is_video=1';break;
					case 'text': $where=' where is_text=1';break;
					*/
				}
			$url="";
			}
			
			$cache=new Cache;
			$sql ="select id,cat_id,post_id,username,id_album ,is_image,is_video,is_text from index_post ".$where." order by ".$order;
			$sql2="select id from index_post ".$where;
		
			$pager = new Pagination($sql,LOAD_ITEMS,4,$url,5,"post");
			$pager->setDebug(false);
			$data[info] = $pager->paginate($cache,$sql2);
			$data['page'] = $pager->get_num_page();
			if($_GET['page'] > $data['page']){
				exit();
			}
			
			
			// END OF GET DATA THEO GET MOTHOD
					// NGUOC LAI THI RENDER GRID ITEM, MASORY WILL APPEND IT
				if($_SESSION['list_news_list'] == 1){
					post_render_grid_item_list($data['info']);
				}else{
					post_render_grid_item($data['info']);
				}
				
				exit();
			
		 }else{
		
		 exit();
		 }
	}
	// END LOAD MORE ITEM WITH GET TYPE VIDEO,TEXT, IMAGE AND CASE ==2-------------------------------------------------
	
	
	
	
	
	
	
	
	
	
	// GET ITEM IN USER PROFILE --------------------------------------------------------
	// case =3, get['ext']
	
	if(isset($_GET['page']) && $_GET['case']==3){
		
		if($_GET['page'] % LOAD_TIME !=0){
		 	
			$order=" id desc";
			$where=" where username='".$_GET['u']."'";
			
			if($_GET['ext']!='album'){
								switch($_GET['ext']){
								case 'picture': $where.='  and is_image=1';break;
								case 'video': $where.=' and is_video=1';break;
								case 'text': $where.=' and is_text=1';	break;
								case 'status': $where.=' and status=0';	break;
								}
								
								
								$cache=new Cache;
								$sql ="select id,cat_id,post_id,username,id_album ,is_image,is_video,is_text from index_post ".$where." order by ".$order;
								$sql2="select id from index_post ".$where;
								$pager = new Pagination($sql,LOAD_ITEMS,5,$url,300,"post");
								$pager->setDebug(false);
								$data[info] = $pager->paginate($cache,$sql2);
								$data['page'] = $pager->get_num_page();
								
								if($_GET['page'] > $data['page']){
									exit();
								}
								post_render_grid_item($data['info']);
								exit();
			}else{
			//GET LIST ALBUM ------
								$cache=new Cache;
								$sql ="select * from album where username='".mysql_real_escape_string($u)."' order by id desc";
								$sql2="select * from album where username='".mysql_real_escape_string($u)."'";
					
								$pager = new Pagination($sql,LOAD_ITEMS,5,'',5,"post");
								$pager->setDebug(false);
								$data[info] = $pager->paginate($cache,$sql2);
								$data['page'] = $pager->get_num_page();
								
								if($_GET['page'] > $data['page']){
									exit();
								}
								
								if($_SESSION['list_news_list'] == 1){
									post_render_grid_item_list($data['info']);
								}else{
									post_render_grid_item($data['info']);
								}
								
								exit();
			//END OF LIST ALBUM
			}
			
		 }else{	 exit();}
		 
	}
	
	//END OF GET ITEM IN USER PROFILE ----------------------
	
	
	//GET ITEM IN ALBUM CASE=5======================
	if(isset($_GET['page']) && $_GET['case']==5){
	
		if($_GET['page'] % LOAD_TIME !=0){
		 	
				$cache=new Cache;
				$sql ="select id,cat_id,post_id,username,id_album ,is_image,is_video,is_text from index_post where id_album=".intval($_GET['id'])." order by id desc";
				$sql2="select id from index_post where id_album=".intval($_GET['id']);
		
			$pager = new Pagination($sql,LOAD_ITEMS,4,$url,5,"post");
			$pager->setDebug(false);
			$data[info] = $pager->paginate($cache,$sql2);
			$data['page'] = $pager->get_num_page();
			if($_GET['page'] > $data['page']){
				exit();
			}
			
			
			// END OF GET DATA THEO GET MOTHOD
					// NGUOC LAI THI RENDER GRID ITEM, MASORY WILL APPEND IT
			
				if($_SESSION['list_news_list'] == 1){
					post_render_grid_item_list($data['info']);
				}else{
					post_render_grid_item($data['info']);
				}
				exit();
			
		 }else{
		
		 exit();
		 }
	}
	//END OF GET ITEM IN ALBUM -----------
	
	
	//RENDER ALBUM LIST ===============================================
	
	if(isset($_GET['page']) && $_GET['case']==4){
		
		if($_GET['page'] % LOAD_TIME !=0){
		 	
			$order=" id desc";
					
			
								
			switch($_GET['ext']){
			case 'views':
			case 'likes':
			case 'comments':
			$order= $_GET['ext']." ".$_GET['sort'];
			break;
			case "date":
			$order= "id ".$_GET['sort'];
		}
								
								$cache=new Cache;
								$sql ="select * from album  order by ".$order;
								$sql2="select id from album";
								
								$pager = new Pagination($sql,3,4,'',5,'album');
								$pager->setDebug(false);
								$data[info] = $pager->paginate($cache,$sql2);
								$data['page'] = $pager->get_num_page();
								if($_GET['page'] > $data['page']){
									exit();
								}
								if($_SESSION['list_news_list'] == 1){
									post_render_grid_item_list($data['info']);
								}else{
									post_render_grid_item($data['info']);
								}
								exit();
			
			
		 }else{	 exit();}
		 
	}
	// END OF RENDER ALBUM LIST------------------------------
	
	
		//RENDER CATEGORY LIST ===============================================
	
	if(isset($_GET['page']) && $_GET['case']==6){
		$id =alphaID($_GET['id'], true);

		if($_GET['page'] % LOAD_TIME !=0){
		 
			$order=" id desc";
		    switch($_GET['ext']){
					case 'views':
					case 'likes':
					case 'comments':
					$order= $_GET['ext']." ".$_GET['sort'];
					break;
					case "date":
					$order= "id ".$_GET['sort'];
			}
			
		if(isset($_GET['type'])){
			
			switch($_GET['type']){
					case 'picture': $where=' where is_image=1 and cat_id='.$id;break;
					case 'video': $where=' where is_video=1 and cat_id='.$id;break;
					case 'text': $where=' where is_text=1 and cat_id='.$id;break;
					
			}
		}else{ $where=' where cat_id='.$id; }
			
								
			$cache=new Cache;					
			$sql ="select id,cat_id,post_id,username,id_album ,is_image,is_video,is_text from index_post ".$where." order by ".$order;
			
			$sql2="select id from index_post ".$where;
			$pager = new Pagination($sql,LOAD_ITEMS,4,'',5,"post");
			
			$pager->setDebug(false);
			$data[info] = $pager->paginate($cache,$sql2);
			$data['page'] = $pager->get_num_page();
			if($_GET['page'] > $data['page']){
				exit();
				
			}else{
			if($_SESSION['list_news_list'] == 1){
					post_render_grid_item_list($data['info']);
				}else{
					post_render_grid_item($data['info']);
				}
			exit();
			}
			
			
		 }else{	 exit();}
	
		 
	}
	// END OF RENDER CATEGORY LIST------------------------------
	
	
	/*
	 *  Get most view threads by current week
	 */
	 if($_GET['rightMostWeekView'] == 1){

	 	$model = new Model();
	 	$model->where = "WEEK(last_update_view, 3) = '" . date('W') . "'";
	   	$model->limit = '5';
	   	$model->order = 'view_week DESC';
	   	$model->getdata('index_post');
	   	$result = $model->fetchAll();
		if($result){

			foreach($result as $post){
				
				$news = get_post($post['id']);

				$resultSend .= '
					<div class="rightItem">
						<a class="wrapRightImage" href="'.url_post($post['id'],'vieww').'"><img width="90" height="60" src="'.$news['image_small'].'" alt=""></a>
						<h4>
							<a class="rightItemTitle" href="'.url_post($post['id'],'vieww').'">'.$news['title'].'</a>
						
						</h4>
						<span class="pull-left font11 margin-right-10"><i class="icon-eye-open"> </i>'.k_format($news['views']).'</span>
						<span class="pull-left font11 margin-right-10"><i class=" icon-thumbs-up-alt"> </i>'.k_format($news['likes']).'</span>
						<span class="pull-left font11 margin-right-10"><i class=" icon-comments"> </i>'.k_format($news['comments']).'</span>
						<span class="pull-left font11 margin-right-10"><a class="rightItemAuthor" href="'.url_user($news['username']).'"><i class=" icon-user"> </i>'.$news['username'].'</a></span>
						<div class="clr"></div>
					</div>
				';
			}
		}
		echo $resultSend;
	   	exit();
	 }
	 
	 /*
	  *  Get most view threads by current week
	 */
	 if($_GET['rightMostMonthView'] == 1){
	 
	 	$model = new Model();
	 	$model->where = "MONTH(last_update_view) = '" . date('m') . "'";
	 	$model->limit = '5';
	 	$model->order = 'view_month DESC';
	 	$model->getdata('index_post');
	 	$result = $model->fetchAll();
	 	if($result){
	 
	 		foreach($result as $post){
	 
	 			$news = get_post($post['id']);
	 
	 			$resultSend .= '
					<div class="rightItem">
						<a class="wrapRightImage" href="'.url_post($post['id'],'viewm').'"><img width="90" height="60" src="'.$news['image_small'].'" alt=""></a>
						<h4>
							<a class="rightItemTitle" href="'.url_post($post['id'],'viewm').'">'.$news['title'].'</a>
						
						</h4>
						<span class="pull-left font11 margin-right-10"><i class="icon-eye-open"> </i>'.k_format($news['views']).'</span>
						<span class="pull-left font11 margin-right-10"><i class=" icon-thumbs-up-alt"> </i>'.k_format($news['likes']).'</span>
						<span class="pull-left font11 margin-right-10"><i class=" icon-comments"> </i>'.k_format($news['comments']).'</span>
						<span class="pull-left font11 margin-right-10"><a class="rightItemAuthor" href="'.url_user($news['username']).'"><i class=" icon-user"> </i>'.$news['username'].'</a></span>
						<div class="clr"></div>
					</div>
				';
	 		}
	 	}
	 	echo $resultSend;
	 	exit();
	}
	 

	if($_GET['ajaxGetNews'] == 1){
		$blankId = $_POST['id'];

		$type = $_POST['postType'];
		$time = time();
		$date = date('Y-m-d', $time);
		switch($type){
			case 'image':
				$table = 'post_image';
				$whereType = 'is_image = 1';
				break;
			case 'video':
				
				$table = 'post_media';
				$whereType = 'is_video = 1';
				break;
			case 'text':
				$table = 'post_text';
				$whereType = 'is_text = 1';
				break;
		}

		
		$model = new Model();

		$model->select = '*';
		$model->where = "post_id = '" . $blankId . "' AND " . $whereType;
		$model->getdata('index_post');
		$result = $model->fetchOne();
		if(!$result){
			$content['data'] = '<div class="alert alert-warning">Bài viết không tồn tại hoặc đã bị xóa, vui lòng thử lại. </div>';
			echo json_encode($content);
			exit();
		}
		
		/*
		 *  Collect post information to update views
		 */
		if(date('z', strtotime($result['last_update_view']) != date('z', $time))){
			$time_views['view_day'] = 1;
		}else{
			if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
		
				$time_views['view_day'] = $result['view_day'] + 1;
			}else{
				$time_views['view_day'] = 1;
			}
		}
		
		if( date('W', strtotime($result['last_update_view'])) != date('W', $time)){
			$time_views['view_week'] = 1;
		}else{
			if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
				$time_views['view_week'] = $result['view_week'] + 1;
			}else{
				$time_views['view_week'] = 1;
			}
		}
		 
		 
		if(date('m', strtotime($result['last_update_view'])) != date('m', $time)){
			$time_views['view_month'] = 1;
		}else{
			if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
				$time_views['view_month'] = $result['view_month'] + 1;
			}else{
				$time_views['view_month'] = 1;
			}
		}
		
		$time_views['last_update_view'] = $date;
		$time_views['views'] = $result['views'] + 1;
		$model->update('index_post', $time_views);
		
		//$model->where = "id = '" . $result['post_id'] . "'";
		$sqlUpdatePostView = "UPDATE $table set views = views + 1 WHERE id = " . $result['post_id'];
		$model->nonquery($sqlUpdatePostView);
		
		$post = get_post($result['id']);

		if(!$post){
			$content['data'] = '<div class="alert alert-warning">Bài viết không tồn tại hoặc đã bị xóa, vui lòng thử lại. </div>';
			echo json_encode($content);
			exit();
		}else{
			
		}
		
		$userData = cache_get_user($post['username']);

		$title = $post['title'];

		$body .= '<div style="margin-top: 10px; text-align: center;">';
		if($post['type'] == 'image'){
			$body .= $post['images_big'];
		}else if($post['type'] == 'video'){
			$body .= $post['embed'];
			//preg_match('/id="(?P<name>\w+)"/', $post['embed'], $matches);
			$body.= '';
			

		}else if($post['type'] == 'text'){
			$body .= $post['description'];
		}

		
		$body .= '';
		$body .= '</div>';
		$body .= '</div><!-- end .contentPopup -->';
		
	
		
		
							$info .= '<ul class="list-inline moreinfo">
										<li> '.k_format($post['views']).' Views</li>
										<li>'.k_format($post['likes']).' Likes</li>
										<li> '.k_format($post['comments']).' Comment</li>
										<li class="pull-right view_time" ><i class="icon-time"></i> '.time_ago($post['date_created']).'</li>  
										<li class="pull-right view_user"><a href="'.url_user($userData['username']).'"><i class="icon-user"></i>'.$userData['username'].'</a> 							
									</li><!-- end .itemInfo -->';
		
		$comment .= '<div class="facebook-comment"><div class="fb-comments" data-href="'.BASE_URL.'index.php?module=news&act=view&id='.$result['id'].'" data-width="600"></div></div>';
		
		
		$content['data'] = '
		    <div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					<h4 class="modal-title">'.$title.'</h4>'.$info.'
					
				</div>
		        <div class="modal-body">
					'.$body.$comment.'
		        </div>
			</div><!-- /.modal-content -->';
			
			echo json_encode($content);
			exit();
	}
	
	
	
	if($_GET['get_modal_report'] == 1){
		$id = $_POST['post_id'];
		$rel = $_POST['rel'];
		$modal = '<div role="dialog" id="modal_report_'.$id.'" data-href="'.$id.'" class="modal" style="display:none;">
				<div class="modal-dialog modal-wide" id="modal_report_inner">
				
					<div class="modal-content" id="modal-content-'.$id.'">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					        Lý do báo xấu
						</div>
						<div class="modal-body">
					        <form id="report_form" class="userPostForm" role="form" method="post" enctype="multipart/form-data">
								<div class="form-group">
									<div class="row">
										<div class="col-md-2">
											<label for="txt_report_content">Nội dung</label>
										</div>
										<div class="col-md-10">
											<textarea class="form-control" placeholder="Nhập nội dung báo xấu..." id="txt_report_content_'.$id.'" rows="3"></textarea>
									</div>
									</div>
								</div>
						
								<div class="form-group">
									<div class="row">
										<div class="col-md-2"></div>
										<div class="col-md-10">
											<button type=submit class="btn btn-primary mySubmit submit_report" data-href="'.$id.'" data-rel="'.$rel.'" id="submit_report_'.$id.'">
												<i class="glyphicon glyphicon-hand-up"></i> <span>Xác nhận</span>
											</button>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div><!-- /.modal-content -->
				</div>
			</div>';
	echo $modal;
	exit();
	}
	
	if($_GET['send_report'] == 1){
		
		if(!$_POST['post_id'] || !$_POST['rel']){
			$errors = array('errors'=>array('txt_report_content'=>'Không tồn tại bài viết này.'));
			echo json_encode($errors);
			exit();
		}
		
		
		$validateAjax = new ValidateAjax();
		$validateAjax->validateDescription($_POST['txt_report_content'], array('required' => true, 'validateAlias'=>'txt_report_content_' . $_POST['post_id'], 'validateDescription' => 'Nội dung'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			$post_id = $_POST['post_id'];
			$rel = $_POST['rel'];
			$model = new Model();
			
			switch($_POST['rel']){
				case 'image':
					$whereRel = "is_image = 1";
					break;
				case 'video':
					$whereRel = "is_video = 1";
					break;
				case 'text':
					$whereRel = "is_text = 1";
					break;
				default:
					$whereRel = "1 = 0";
					break;
			}
			$model->select = "id";
			$model->where = "post_id = '" . $post_id . "' AND $whereRel";
			$model->getdata('index_post');
			$result = $model->fetchOne();
			if(!$result){
				echo 'here';
				$errors = $validateAjax->getErrorMessages();
				echo json_encode($errors);
				exit();
			}
			
			$table = 'report_post';
			$data['index_post_id'] = $result['id'];
			
			$data['ip'] = get_ip();
			$data['username'] = $_SESSION['user']['username'];
			$data['date_report'] = date("Y-m-d H:i:s");
			$data['content'] = $_POST['txt_report_content'];
			$model->where = "";
			$model->insert($table, $data);
			 
			echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
			exit();
		}
	}
	
	
	if($_GET['detail_ajax_get_post'] == 1){

				$index_id = url_decode($_POST['id'],'post');
				
				$blankId = $index_id;
				
				$post = cache_get_modal_array($index_id);

				$time = time();
				
				$date = date('Y-m-d', $time);

				
				if($post){
					$model = new Model();
					$model->where = "id = '" . $post['pid'] . "'";
					$model->getdata('index_post');
					$result = $model->fetchOne();

					/*
					 *  Collect post information to update views
					*/
					if(date('z', strtotime($result['last_update_view']) != date('z', $time))){
						$time_views['view_day'] = 1;
					}else{
						if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
								
							$time_views['view_day'] = $result['view_day'] + 1;
						}else{
							$time_views['view_day'] = 1;
						}
					}
						
					if( date('W', strtotime($result['last_update_view'])) != date('W', $time)){
						$time_views['view_week'] = 1;
					}else{
						if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
							$time_views['view_week'] = $result['view_week'] + 1;
						}else{
							$time_views['view_week'] = 1;
						}
					}
				
				
					if(date('m', strtotime($result['last_update_view'])) != date('m', $time)){
						$time_views['view_month'] = 1;
					}else{
						if(date('Y', strtotime($result['last_update_view'])) == date('Y', $time)){
							$time_views['view_month'] = $result['view_month'] + 1;
						}else{
							$time_views['view_month'] = 1;
						}
					}
						
					$time_views['last_update_view'] = $date;
					$time_views['views'] = $result['views'] + 1;

					
					$model->where = "id = '".$result['id']."'";
					$model->update('index_post', $time_views);
						
				
					if($result['is_video'] == 1){
						$table = 'post_video';
					}else if($result['is_image'] == 1){
						$table = 'post_image';
					}else if($result['is_text'] == 1){
						$table = 'post_text';
					}
					
					$model->where = "id = '" . $result['post_id'] . "'";
					$model->getdata($table);
					$resultPost = $model->fetchOne();
					
					$viewsPost = array('views' => $resultPost['views'] + 1);
					$model->update($table, $viewsPost);
					//$model->where = "id = '" . $result['post_id'] . "'";
					//$sqlUpdatePostView = "UPDATE $table set views = '" . $resultPost['views'] . "' + 1 WHERE id = '" . $result['post_id'] . "'";
					//$model->nonquery($sqlUpdatePostView);
				}
				
				if($post['type'] == 'video'){
					$post['detail_main_content'] = $post['embed'];
				}
				
				if($post['type'] == 'image'){
					$post['detail_main_content'] = $post['images_big'];
				}
				
				if($post['type'] == 'text'){
					$post['detail_main_content'] = $post['description'];
				}
				
				$post['pid'] = url_encode_post($post['pid']);
					
				$post['user'] = cache_get_user($post['username']);
				
				$post['user']['avatar'] = get_image($post['user']['avatar'], 'avatar/100');
				$post['user']['link'] = url_user($post['user']['username']);
				$post['user']['likes'] = k_format($post['user']['likes']);
				$post['user']['views'] = k_format($post['user']['views']);
				$post['user']['comments'] = k_format($post['user']['comments']);
				$data['post'] = $post;
				echo json_encode($data);
				exit();
			
			
			
		
	}// End of $_GET['detail_ajax_get_post'] == 1
	
	
	if($_GET['setModeView'] == 1){

		$id = $_POST['id'];
		if($id == 'gridMode'){
			$_SESSION['list_news_list'] = false;
		}else if($id == 'listMode'){
			$_SESSION['list_news_list'] = true;
		}else{
			exit();
		}
		exit();
	}
}